<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_Article extends Controller_ClientTemplate
{
    
    public function action_index()
    {
        $href = '/'.Request::$current->param('href', '');
        
        if($href != '/'){
            $article = DB::query(Database::SELECT, 'SELECT * FROM `articles` WHERE `href`=:href LIMIT 1')
                      ->param(':href', $href)
                      ->as_object()
                      ->execute();
            
            
            if($article->count()){
                $article = $article->current();
                $this->template->title = $article->html_title;
                $this->template->keywords = $article->html_keyword;
                $this->template->description = $article->html_description;
                
                $this->template->content = View::factory('content')
                                                ->set('title', $article->html_title)
                                                ->set('content', $article->content);
            } else {
                $this->auto_render = false;
                
                $this->response->status(404);
                $this->response->body(Request::factory('error/404')->execute());
            }
        } else { 
            
            $article = DB::query(Database::SELECT, 'SELECT a.href as href, a.html_title as html_title, a.content as content, 
                                                           a.html_keyword as html_keyword, a.html_description as html_description
                                                    FROM `chapters` as c
                                                    LEFT JOIN `articles` as a ON a.href=c.href
                                                    WHERE c.parent_id=0 
                                                    ORDER BY c.pos ASC LIMIT 1')
                        ->as_object()                            
                        ->execute();
            
             if($article->count()){ 
                $this->template->scripts = array('js/jquery.roundabout.js');
                
                $article = $article->current();
                $this->template->title = $article->html_title;
                $this->template->keywords = $article->html_keyword;
                $this->template->description = $article->html_description;
                $this->template->content = View::factory('main')->set('content', $article->content)->render();
            } else {
                $this->auto_render = false;                
                $this->response->status(404);
                $this->response->body(Request::factory('error/404')->execute());
            } 
        }
    }
}